package ar.Location.Api.GooglePlace;

import java.util.ArrayList;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import ar.Location.PlaceObject.Place;
import ar.globals.Globals;

public class GooglePlaceHandler extends DefaultHandler {

	boolean is_entered_result_TAG = false;
	public String categoryName = "";

	GooglePlace gPlace = null;
	ArrayList<Place> listPlaces = null;
	StringBuffer stringBuffer = new StringBuffer();

	public GooglePlaceHandler(String name) {
		categoryName = name;
	}

	@Override
	public void startDocument() throws SAXException {
		// TODO Auto-generated method stub
		listPlaces = new ArrayList<Place>();
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		// TODO Auto-generated method stub

		stringBuffer.setLength(0);

		if (localName.equals("result")) {
			is_entered_result_TAG = true;
			gPlace = new GooglePlace(categoryName);
		}
	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		// TODO Auto-generated method stub
		stringBuffer.append(ch, start, length);
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		// TODO Auto-generated method stub
		String innerText = stringBuffer.toString().trim();

		if (is_entered_result_TAG) {
			if (localName.equals("name")) {
				gPlace.name = innerText;
			}
			if (localName.equals("vicinity")) {
				gPlace.address = innerText;
			}
			if (localName.equals("lat")) {
				gPlace.latitude = innerText;
			}
			if (localName.equals("lng")) {
				gPlace.longitude = innerText;
			}
			if (localName.equals("rating")) {
				gPlace.rank = innerText;
			}
			if (localName.equals("icon")) {
				gPlace.imageUrl = innerText;
			}
			if (localName.equals("reference")) {
				gPlace.other = innerText;
			}
		}

		if (localName.equals("result")) {
			listPlaces.add(gPlace);
			is_entered_result_TAG = false;
		}
	}

	@Override
	public void endDocument() throws SAXException {
		// TODO Auto-generated method stub
		super.endDocument();
	}

	public ArrayList<Place> getListResults() {
		if (listPlaces != null && listPlaces.size() > 0) {
			int size = listPlaces.size();
			if (size > Globals.MAX_NUMBER_OF_SEARCHED_LOCATIONS) {
				ArrayList<Place> newList = new ArrayList<Place>();
				for (int i = 0; i < Globals.MAX_NUMBER_OF_SEARCHED_LOCATIONS; i++) {
					newList.add(listPlaces.get(i));
				}
				listPlaces.clear();
				return newList;
			} else {
				return listPlaces;
			}
		}
		return null;
	}
}
